package org.jeecg.modules.wmhb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.constant.FillRuleConstant;
import org.jeecg.common.constant.UserConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.system.vo.SysDepartModel;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.common.system.vo.SelectTreeModel;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.wmhb.service.*;
import org.jeecg.modules.wmhb.util.WmhbUtil;
import org.jeecg.modules.wmhb.entity.*;
import org.jeecg.modules.wmhb.mapper.WmTaskMapper;
import org.jeecg.modules.wmhb.vo.WmDepartRemainTaskVo;
import org.jeecg.modules.wmhb.vo.WmProjectStatisticVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;
import java.io.*;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.util.CollectionUtils;

/**
 * @Description: 任务表
 * @Author: jeecg-boot
 * @Date:   2024-09-05
 * @Version: V1.0
 */
@Service
public class WmTaskServiceImpl extends ServiceImpl<WmTaskMapper, WmTask> implements IWmTaskService {

    @Autowired
    ISysBaseAPI sysBaseApi;
    @Autowired
    private IWmTaskFlowService wmTaskFlowService;
    @Autowired
    private IWmTaskLogService wmTaskLogService;
    @Autowired
    private IWmTaskBomService wmTaskBomService;
    @Autowired
    private ISysDictService sysDictService;
    @Autowired
    private ISysUserService sysUserService;

    @Override
    public void addWmTask(WmTask wmTask) {
        //新增时设置hasChild为0
        wmTask.setHasChild(IWmTaskService.NOCHILD);
        if(oConvertUtils.isEmpty(wmTask.getPid())){
            wmTask.setPid(IWmTaskService.ROOT_PID_VALUE);
            wmTask.setAncestors(IWmTaskService.ANCESTORS);
        }else{
            //如果当前节点父ID不为空 则设置父节点的hasChildren 为1
            WmTask parent = baseMapper.selectById(wmTask.getPid());
            if(parent!=null && !"1".equals(parent.getHasChild())){
                parent.setHasChild("1");
                baseMapper.updateById(parent);
            }

            if(parent != null) {
                wmTask.setAncestors(parent.getAncestors() + "," + parent.getId());
            }
        }
        baseMapper.insert(wmTask);
    }

    @Override
    public void updateWmTask(WmTask wmTask) {
        WmTask entity = this.getById(wmTask.getId());
        if(entity==null) {
            throw new JeecgBootException("未找到对应实体");
        }
        String old_pid = entity.getPid();
        String new_pid = wmTask.getPid();
        if(!old_pid.equals(new_pid) && !oConvertUtils.isEmpty(new_pid)) {
            updateOldParentNode(old_pid);
//            if(oConvertUtils.isEmpty(new_pid)){
//                wmTask.setPid(IWmTaskService.ROOT_PID_VALUE);
//            }
            if(!IWmTaskService.ROOT_PID_VALUE.equals(wmTask.getPid())) {
                baseMapper.updateTreeNodeStatus(wmTask.getPid(), IWmTaskService.HASCHILD);
            }
        }
        baseMapper.updateById(wmTask);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteWmTask(String id) throws JeecgBootException {
        //查询选中节点下所有子节点一并删除
        id = this.queryTreeChildIds(id);
        if(id.indexOf(",")>0) {
            StringBuffer sb = new StringBuffer();
            String[] idArr = id.split(",");
            for (String idVal : idArr) {
                if(idVal != null){
                    WmTask wmTask = this.getById(idVal);
                    String pidVal = wmTask.getPid();
                    //查询此节点上一级是否还有其他子节点
                    List<WmTask> dataList = baseMapper.selectList(new QueryWrapper<WmTask>().eq("pid", pidVal).notIn("id",Arrays.asList(idArr)));
                    boolean flag = (dataList == null || dataList.size() == 0) && !Arrays.asList(idArr).contains(pidVal) && !sb.toString().contains(pidVal);
                    if(flag){
                        //如果当前节点原本有子节点 现在木有了，更新状态
                        sb.append(pidVal).append(",");
                    }
                }
            }
            //批量删除节点
            baseMapper.deleteBatchIds(Arrays.asList(idArr));
            //修改已无子节点的标识
            String[] pidArr = sb.toString().split(",");
            for(String pid : pidArr){
                this.updateOldParentNode(pid);
            }
        }else{
            WmTask wmTask = this.getById(id);
            if(wmTask==null) {
                throw new JeecgBootException("未找到对应实体");
            }
            updateOldParentNode(wmTask.getPid());
            baseMapper.deleteById(id);
        }
    }

    @Override
    public List<WmTask> queryTreeListNoPage(QueryWrapper<WmTask> queryWrapper) {
        List<WmTask> dataList = baseMapper.selectList(queryWrapper);
        List<WmTask> mapList = new ArrayList<>();
        for(WmTask data : dataList){
            String pidVal = data.getPid();
            //递归查询子节点的根节点
            if(pidVal != null && !IWmTaskService.NOCHILD.equals(pidVal)){
                WmTask rootVal = this.getTreeRoot(pidVal);
                if(rootVal != null && !mapList.contains(rootVal)){
                    mapList.add(rootVal);
                }
            }else{
                if(!mapList.contains(data)){
                    mapList.add(data);
                }
            }
        }
        return mapList;
    }

    @Override
    public List<SelectTreeModel> queryListByCode(String parentCode) {
        String pid = ROOT_PID_VALUE;
        if (oConvertUtils.isNotEmpty(parentCode)) {
            LambdaQueryWrapper<WmTask> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(WmTask::getPid, parentCode);
            List<WmTask> list = baseMapper.selectList(queryWrapper);
            if (list == null || list.size() == 0) {
                throw new JeecgBootException("该编码【" + parentCode + "】不存在，请核实!");
            }
            if (list.size() > 1) {
                throw new JeecgBootException("该编码【" + parentCode + "】存在多个，请核实!");
            }
            pid = list.get(0).getId();
        }
        return baseMapper.queryListByPid(pid, null);
    }

    @Override
    public List<SelectTreeModel> queryListByPid(String pid) {
        if (oConvertUtils.isEmpty(pid)) {
            pid = ROOT_PID_VALUE;
        }
        return baseMapper.queryListByPid(pid, null);
    }

    /**
     * 根据所传pid查询旧的父级节点的子节点并修改相应状态值
     * @param pid
     */
    private void updateOldParentNode(String pid) {
        if(!IWmTaskService.ROOT_PID_VALUE.equals(pid)) {
            Long count = baseMapper.selectCount(new QueryWrapper<WmTask>().eq("pid", pid));
            if(count==null || count<=1) {
                baseMapper.updateTreeNodeStatus(pid, IWmTaskService.NOCHILD);
            }
        }
    }

    /**
     * 递归查询节点的根节点
     * @param pidVal
     * @return
     */
    private WmTask getTreeRoot(String pidVal){
        WmTask data =  baseMapper.selectById(pidVal);
        if(data != null && !IWmTaskService.ROOT_PID_VALUE.equals(data.getPid())){
            return this.getTreeRoot(data.getPid());
        }else{
            return data;
        }
    }

    /**
     * 根据id查询所有子节点id
     * @param ids
     * @return
     */
    private String queryTreeChildIds(String ids) {
        //获取id数组
        String[] idArr = ids.split(",");
        StringBuffer sb = new StringBuffer();
        for (String pidVal : idArr) {
            if(pidVal != null){
                if(!sb.toString().contains(pidVal)){
                    if(sb.toString().length() > 0){
                        sb.append(",");
                    }
                    sb.append(pidVal);
                    this.getTreeChildIds(pidVal,sb);
                }
            }
        }
        return sb.toString();
    }

    /**
     * 递归查询所有子节点
     * @param pidVal
     * @param sb
     * @return
     */
    private StringBuffer getTreeChildIds(String pidVal,StringBuffer sb){
        List<WmTask> dataList = baseMapper.selectList(new QueryWrapper<WmTask>().eq("pid", pidVal));
        if(dataList != null && dataList.size()>0){
            for(WmTask tree : dataList) {
                if(!sb.toString().contains(tree.getId())){
                    sb.append(",").append(tree.getId());
                }
                this.getTreeChildIds(tree.getId(),sb);
            }
        }
        return sb;
    }

    @Override
    public String checkItemCodeUnique(WmTask wmTask) {
        WmTask item = baseMapper.checkItemCodeUnique(wmTask.getCode(), wmTask.getPid(), wmTask.getType(), wmTask.getWmTaskbookId());
        if(item != null && !wmTask.getId().equals(item.getId())){
            return UserConstant.NOT_UNIQUE;
        }
        return UserConstant.UNIQUE;
    }

    @Override
    public String checkItemNameUnique(WmTask wmTask) {
        WmTask item = baseMapper.checkItemNameUnique(wmTask.getName(), wmTask.getPid(), wmTask.getType(), wmTask.getWmTaskbookId());
        if(item != null && !wmTask.getId().equals(item.getId())){
            return UserConstant.NOT_UNIQUE;
        }
        return UserConstant.UNIQUE;
    }

    @Override
    public boolean checkHasItem(String id) {
        int num = baseMapper.hasItemById(id);
        return num >0 ? true:false;
    };

    @Override
    public WmTask importComponentBom(BOMNode bomNode, WmTask wmTaskParent){
        WmTask wmTask = new WmTask();        //初始化任务
        wmTask.setWmTaskbookId(wmTaskParent.getWmTaskbookId());
        wmTask.setStatus(wmTaskParent.getStatus());
        wmTask.setName(bomNode.getName());
        wmTask.setItemOrProduct(bomNode.getItemOrProduct());
        wmTask.setCode(bomNode.getCode());
        wmTask.setBatchNo(wmTaskParent.getBatchNo());
        wmTask.setEnableFlag(wmTaskParent.getEnableFlag());
        //wmTask.setQuantity(bomNode.getQuantity() * wmTaskParent.getQuantity());
        wmTask.setQuantity(bomNode.getQuantity());
        wmTask.setPid(wmTaskParent.getId());
        wmTask.setAncestors(wmTaskParent.getAncestors() + "," + wmTaskParent.getId());
        wmTask.setCurrentNodeId(wmTaskParent.getCurrentNodeId());
        wmTask.setCurrentNodeIndex(wmTaskParent.getCurrentNodeIndex());
        wmTask.setCurrentNodeTime(new Date());
        wmTask.setSpecification(bomNode.getSpecification());
        wmTask.setUnitOfMeasure(bomNode.getUnitOfMeasure());
        wmTask.setIsSendUnit(bomNode.getIsSendUnit());
        wmTask.setCanEditFlow(wmTaskParent.getCanEditFlow());
        wmTask.setBuId(wmTaskParent.getBuId());
        wmTask.setTaskbookType(wmTaskParent.getTaskbookType());
        wmTask.setWmContractProductId(wmTaskParent.getWmContractProductId());
        wmTask.setProgress(wmTaskParent.getProgress());
        wmTask.setPlanEndTime(wmTaskParent.getPlanEndTime());
        wmTask.setPlanBeginTime(wmTaskParent.getPlanBeginTime());
        wmTask.setFactBeginTime(wmTaskParent.getFactBeginTime());
        wmTask.setItemType(bomNode.getItemType());
        wmTask.setCurrentVersion(wmTaskParent.getCurrentVersion());

        if(!StringUtils.isEmpty(bomNode.getTaskType())) {
            wmTask.setType(bomNode.getTaskType());
        }

        if(!StringUtils.isEmpty(wmTaskParent.getOrderTaskId())) {
            wmTask.setOrderTaskId(wmTaskParent.getOrderTaskId());
        }

        if(!StringUtils.isEmpty(bomNode.getSize())) {
            wmTask.setSize(bomNode.getSize());
        }

        addWmTaskByVersion(wmTask);

        return wmTask;
    };

    @Override
    public WmTask selectTaskByCodeAndTaskbookId(String code, String wmTaskbookId){
        LambdaQueryWrapper<WmTask> queryWrapperTask = new LambdaQueryWrapper<>();
        queryWrapperTask.eq(WmTask::getCode, code).eq(WmTask::getWmTaskbookId, wmTaskbookId).last("LIMIT 1");
        WmTask wmTask = getOne(queryWrapperTask);             //任务
        return wmTask;
    };

    @Override
    public WmTask selectTaskByCodeAndTaskParent(String pCode, WmTask wmTaskRoot){
        LambdaQueryWrapper<WmTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmTask::getCode, pCode).eq(WmTask::getWmTaskbookId, wmTaskRoot.getWmTaskbookId());
        if (wmTaskRoot.getCurrentVersion() == null) {
            queryWrapper.isNull(WmTask::getCurrentVersion);
        } else {
            queryWrapper.eq(WmTask::getCurrentVersion, wmTaskRoot.getCurrentVersion());
        }

        queryWrapper.last("LIMIT 1");
        WmTask wmTask = getOne(queryWrapper);             //任务
        return wmTask;
    };

    @Override
    public Map<String, Object> transferTaskbook(WmTaskbook wmTaskbookOld, WmTaskbook wmTaskbookNew, WmTaskbookFlow wmTaskbookFlow){
        Map<String, Object> result = new HashMap<>();
        List<WmTask> wmTaskListNew = new ArrayList<>();
        //1、获取没有子节点的任务列表，通过其ancestors属性生成新任务书下所有节点的任务
        LambdaQueryWrapper<WmTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmTask::getWmTaskbookId, wmTaskbookOld.getId());
        List<WmTask> wmTaskList = list(queryWrapper);
        if(CollectionUtils.isEmpty(wmTaskList)){
            throw new RuntimeException("产品任务列表为空，请先添加");
        }

        if(wmTaskbookFlow.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_PRODUCE)){
            if (wmTaskbookOld.getIsTransferProduceTaskbook().equals(UserConstant.SYS_YES)) {
                throw new RuntimeException("设计任务书已被转换过为生产任务书");
            }
            wmTaskbookOld.setIsTransferProduceTaskbook(UserConstant.SYS_YES);
        }
        else if(wmTaskbookFlow.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_PURCHASE)){
            if (wmTaskbookOld.getIsTransferPurchaseTaskbook().equals(UserConstant.SYS_YES)) {
                throw new RuntimeException("工艺任务书已被转换过为采购任务书");
            }
            wmTaskbookOld.setIsTransferPurchaseTaskbook(UserConstant.SYS_YES);
        }

        //2、转换为生产任务书或采购任务书
        for(WmTask wmTask: wmTaskList){
            List<WmTask> wmTasks = generateTask(wmTaskbookNew, wmTask); //通过设计任务或工艺任务转换新的任务
            wmTaskListNew.addAll(wmTasks);
        }
        wmTaskbookOld.setStatus(UserConstant.TASK_STATUS_FINISHED);

        result.put("entity", wmTaskbookOld);
        // 将List序列化为Object
        Object serializedList = serializeList(wmTaskListNew);
        result.put("list", serializedList);
        return result;
    };

    // 序列化List方法
    private static Object serializeList(List<?> list) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try (ObjectOutputStream out = new ObjectOutputStream(bos)) {
            out.writeObject(list);
            out.flush();
            return bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 从其他任务书的任务转换为新任务书的任务  参数为新任务书和原有任务
     * @param wmTaskbookNew
     * @param wmTaskOriginal
     */
    private List<WmTask> generateTask(WmTaskbook wmTaskbookNew, WmTask wmTaskOriginal){
        List<WmTask> wmTaskListNew = new ArrayList<>();
        List<String> ancestorList = Arrays.asList(wmTaskOriginal.getAncestors().split(","));
        WmTask wmTaskParentNew = new WmTask();
        //祖先节点循环复制
        for(String ancestor: ancestorList){
            //去除ID为0的
            if(!StringUtils.isEmpty(ancestor) && !ancestor.equals("0")){
                //判断任务是否存在
                WmTask wmTaskAncestor = getById(ancestor);//祖先任务
                //复制祖先节点并保存为新节点，存在则不能新生成
                WmTask wmTask = findTaskOfTaskbook(ancestor, wmTaskbookNew.getId());
                if(wmTask == null) {
                    wmTaskParentNew = copyTaskToSave(wmTaskbookNew, wmTaskAncestor, wmTaskParentNew);
                    wmTaskListNew.add(wmTaskParentNew);
                }
                else{
                    BeanUtils.copyProperties(wmTask, wmTaskParentNew);
                }
            }
        }

        //复制叶子节点(从当前任务的ancestors链条看，任务本身为叶子节点)并保存为新节点，存在则不能新生成
        WmTask wmTask = findTaskOfTaskbook(wmTaskOriginal.getId(), wmTaskbookNew.getId());
        if(wmTask == null) {
            if(!StringUtils.isEmpty(wmTaskOriginal.getIsStartPoint()) && wmTaskOriginal.getIsStartPoint().equals(UserConstant.SYS_YES)){
                wmTaskOriginal.setIsStartPoint(UserConstant.SYS_YES);
            }
            else{
                wmTaskOriginal.setIsStartPoint(UserConstant.SYS_NO);
            }
            WmTask leafTask = copyTaskToSave(wmTaskbookNew, wmTaskOriginal, wmTaskParentNew);
            wmTaskListNew.add(leafTask);

            if(wmTaskOriginal.getHasChild().equals(UserConstant.HAS_CHILD_NO)) {
                //初始化任务日志（一键转换工艺任务书和设计任务书时，叶子节点为设计起点任务）
                wmTaskLogService.initTaskLog(leafTask);
            }
        }

        return wmTaskListNew;
    }

    //查询任务书中的某名称的任务是否存在
    private WmTask findTaskOfTaskbook(String wmTaskId, String wmTaskbookId){
        //判断任务是否存在
        WmTask wmTask = getById(wmTaskId);//任务
        LambdaQueryWrapper<WmTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmTask::getName, wmTask.getName()).eq(WmTask::getWmTaskbookId, wmTaskbookId).last("LIMIT 1"); //同一产品同一事业部下的同一类型任务书只能有一个
        WmTask wmTaskExist = getOne(queryWrapper);
        if(wmTaskExist != null){
            return wmTaskExist;
        }
        else{
            return null;
        }
    }

    //拷贝设计任务书的任务到新的任务书任务
    private WmTask copyTaskToSave(WmTaskbook wmTaskbook, WmTask wmTaskOriginal, WmTask wmTaskParentNew){
        WmTask wmTaskNew = new WmTask();
        wmTaskNew.setName(wmTaskOriginal.getName());
        wmTaskNew.setWmTaskbookId(wmTaskbook.getId());
        wmTaskNew.setCode(wmTaskOriginal.getCode());
        wmTaskNew.setWmContractProductId(wmTaskOriginal.getWmContractProductId());
        wmTaskNew.setWmItemId(wmTaskOriginal.getWmItemId());
        wmTaskNew.setTaskbookType(wmTaskbook.getTaskbookType());
        wmTaskNew.setEnableFlag(UserConstant.ENABLE_FLAG_YES);
        wmTaskNew.setTenantId(wmTaskOriginal.getTenantId());
        wmTaskNew.setSysOrgCode(wmTaskOriginal.getSysOrgCode());
        wmTaskNew.setItemOrProduct(wmTaskOriginal.getItemOrProduct());
        wmTaskNew.setUnitOfMeasure(wmTaskOriginal.getUnitOfMeasure());
        wmTaskNew.setQuantity(wmTaskOriginal.getQuantity());
        wmTaskNew.setCanEditFlow(wmTaskOriginal.getCanEditFlow());
        wmTaskNew.setIsSendUnit(wmTaskOriginal.getIsSendUnit());
        wmTaskNew.setSpecification(wmTaskOriginal.getSpecification());
        wmTaskNew.setDesignFile(wmTaskOriginal.getDesignFile());
        wmTaskNew.setBuId(wmTaskbook.getBuId());
        wmTaskNew.setItemType(wmTaskOriginal.getItemType());
        wmTaskNew.setDesignUserId(wmTaskOriginal.getDesignUserId());
        wmTaskNew.setProcessUserId(wmTaskOriginal.getProcessUserId());

        if(!StringUtils.isEmpty(wmTaskOriginal.getType())) {
            wmTaskNew.setType(wmTaskOriginal.getType());
        }
        else{
            wmTaskNew.setType(UserConstant.TASK_TYPE_SELF);
        }

        if(!StringUtils.isEmpty(wmTaskParentNew.getId())){
            wmTaskNew.setPid(wmTaskParentNew.getId());
            wmTaskNew.setAncestors(wmTaskParentNew.getAncestors() + "," + wmTaskParentNew.getId());
            if(!StringUtils.isEmpty(wmTaskParentNew.getIsStartPoint()) && wmTaskParentNew.getIsStartPoint().equals(UserConstant.SYS_YES)) {
                //如果父任务是设计起点任务，则任务的报料任务ID为父任务ID
                wmTaskNew.setOrderTaskId(wmTaskParentNew.getId());
            }
            if (!StringUtils.isEmpty(wmTaskParentNew.getOrderTaskId())) {
                //如果父任务的报料任务ID不为空，则新任务报料任务ID为父任务的报料任务ID
                wmTaskNew.setOrderTaskId(wmTaskParentNew.getOrderTaskId());
            }
        }
        else{
            wmTaskNew.setPid(IWmTaskService.ROOT_PID_VALUE);
            wmTaskNew.setAncestors(IWmTaskService.ANCESTORS);
        }

        if(!StringUtils.isEmpty(wmTaskOriginal.getIsStartPoint())) {
            wmTaskNew.setIsStartPoint(wmTaskOriginal.getIsStartPoint());
        }

        addWmTask(wmTaskNew);

        //设计任务书转生产任务书时，新生成任务BOM用于报料
        if(wmTaskOriginal.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_DESIGN) && wmTaskOriginal.getIsStartPoint().equals(UserConstant.SYS_YES)){
            //获取设计起点任务的物料清单
            List<WmTaskBom> wmTaskBomList = wmTaskBomService.listByWmTaskId(wmTaskOriginal.getId());
            for(WmTaskBom wmTaskBomItem: wmTaskBomList) {
                WmTaskBom wmTaskBom = new WmTaskBom();
                wmTaskBom.setSpecification(wmTaskBomItem.getSpecification());
                wmTaskBom.setCode(wmTaskBomItem.getCode());
                wmTaskBom.setName(wmTaskBomItem.getName());
                wmTaskBom.setWmTaskId(wmTaskNew.getId()); //报料任务ID
                wmTaskBom.setUnitOfMeasure(wmTaskBomItem.getUnitOfMeasure());
                wmTaskBom.setItemType(wmTaskBomItem.getItemType());
                wmTaskBom.setStatus(UserConstant.TASKBOM_PREPARE);
                wmTaskBom.setProcessNo(wmTaskBomItem.getProcessNo());
                wmTaskBom.setGotowhere(wmTaskBomItem.getGotowhere());
                wmTaskBom.setSize(wmTaskBomItem.getSize());
                wmTaskBom.setMaterial(wmTaskBomItem.getMaterial());
                wmTaskBom.setRemark(wmTaskBomItem.getRemark());
                wmTaskBom.setCaiLiao(wmTaskBomItem.getCaiLiao());
                wmTaskBom.setGuiGe(wmTaskBomItem.getGuiGe());
                wmTaskBom.setGbNumber(wmTaskBomItem.getGbNumber());
                wmTaskBom.setMingCheng(wmTaskBomItem.getMingCheng());
                wmTaskBom.setOtherRequire(wmTaskBomItem.getOtherRequire());
                wmTaskBom.setNeedNum(wmTaskBomItem.getNeedNum());
                wmTaskBom.setTotalWeight(wmTaskBomItem.getTotalWeight());
                wmTaskBom.setPurchaseNum(wmTaskBomItem.getPurchaseNum());
                wmTaskBom.setSysOrgCode(wmTaskBomItem.getSysOrgCode());
                wmTaskBom.setTenantId(wmTaskBomItem.getTenantId());
                wmTaskBomService.save(wmTaskBom);
            }
        }
        wmTaskNew.setHasChild(null); //不更新该属性，addWmTask方法中已经更新过
        return wmTaskNew;
    }

    @Override
    public List<WmTask> selectTaskChildrenInIdList(WmTask wmTaskParent, List<String> taskIdList){
        List<WmTask> wmTaskList = queryTaskChildrenInIdList(wmTaskParent, taskIdList);
        return wmTaskList;
    };

    /**
     * 递归获取设计任务子任务列表
     * @param wmTaskParent
     * @param taskIdList
     * @return
     */
    private List<WmTask> queryTaskChildrenInIdList(WmTask wmTaskParent, List<String> taskIdList){
        List<WmTask> wmTaskListFinal = new ArrayList<>();
        LambdaQueryWrapper<WmTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmTask::getPid, wmTaskParent.getId());
        if(wmTaskParent.getCurrentVersion() == null){
            queryWrapper.isNull(WmTask::getCurrentVersion);
        }
        else{
            queryWrapper.eq(WmTask::getCurrentVersion, wmTaskParent.getCurrentVersion());
        }
        List<WmTask> wmTaskList = list(queryWrapper);
        for(WmTask wmTask: wmTaskList){
            List<WmTask> taskChildren = queryTaskChildrenInIdList(wmTask, taskIdList);
            wmTask.setTaskbookStatus(wmTaskParent.getTaskbookStatus());
            wmTask.setChildren(taskChildren);
            wmTask.setKey(wmTask.getId());
            wmTask.setParentId(wmTask.getPid());
            wmTask.setTitle(wmTask.getName());
            wmTask.setIsLeaf(taskChildren.isEmpty());
            //设计任务ID必须在taskIdListQuery中（起点任务ID及其父辈ID列表），起点设计任务以下节点不返回
            if(!taskIdList.isEmpty() && taskIdList.contains(wmTask.getId())) {
                wmTaskListFinal.add(wmTask);
            }
        }
        return wmTaskListFinal;
    }

    /**
     * 递归获取任务子任务列表
     * @param wmTaskParent
     * @return
     */
    private List<WmTask> queryTaskChildren(WmTask wmTaskParent){
        List<WmTask> wmTaskListFinal = new ArrayList<>();
        //1、如果是作为菜单树，只到发货单位为止，2、如果不是菜单树，遍历所有任务
        LambdaQueryWrapper<WmTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmTask::getPid, wmTaskParent.getId());
        if(wmTaskParent.getCurrentVersion() == null){
            queryWrapper.isNull(WmTask::getCurrentVersion);
        }
        else{
            queryWrapper.eq(WmTask::getCurrentVersion, wmTaskParent.getCurrentVersion());
        }
        List<WmTask> wmTaskList = list(queryWrapper);
        for (WmTask wmTask : wmTaskList) {
            List<WmTask> taskChildren = queryTaskChildren(wmTask);
            wmTask.setTaskbookStatus(wmTaskParent.getTaskbookStatus());
            wmTask.setChildren(taskChildren);
            wmTask.setKey(wmTask.getId());
            wmTask.setParentId(wmTask.getPid());
            wmTask.setTitle(wmTask.getName());
            wmTask.setIsLeaf(taskChildren.isEmpty());
            if(!StringUtils.isEmpty(wmTask.getCurrentNodeId())) {
                SysDepartModel sysDepartModel = sysBaseApi.selectAllById(wmTask.getCurrentNodeId());
                wmTask.setCurrentNodeId_dictText(sysDepartModel.getDepartName());
            }
            wmTaskListFinal.add(wmTask);
        }

        return wmTaskListFinal;
    }

    @Override
    public List<WmTask> selectChildTaskList(WmTask wmTask){
        LambdaQueryWrapper<WmTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.likeRight(WmTask::getAncestors, wmTask.getAncestors() + "," + wmTask.getId()).eq(WmTask::getWmTaskbookId, wmTask.getWmTaskbookId());
        if(wmTask.getCurrentVersion() == null){
            queryWrapper.isNull(WmTask::getCurrentVersion);
        }
        else{
            queryWrapper.eq(WmTask::getCurrentVersion, wmTask.getCurrentVersion());
        }
        List<WmTask> wmTaskList = list(queryWrapper);
        return wmTaskList;
    };

    @Override
    public List<WmTask> selectAncestorTaskList(List<WmTask> wmTaskList, List<String> contractProductIdList){
        List<String> idList = new ArrayList<>();
        List<WmTask> ancestorTaskList =  new ArrayList<>();
        for(WmTask wmTask: wmTaskList){
            List<String> ancestorIdList = Arrays.asList(wmTask.getAncestors().split(","));
            if(ancestorIdList.size() > 1) {
                //祖先是别人
                WmTask ancestorTask = getById(ancestorIdList.get(1));
                if(!idList.contains(ancestorTask.getId()) && contractProductIdList.contains(ancestorTask.getWmContractProductId())){
                    idList.add(ancestorTask.getId());
                    ancestorTaskList.add(ancestorTask);
                }
            }
            else {
                //祖先是自己
                if(!idList.contains(wmTask.getId()) && contractProductIdList.contains(wmTask.getWmContractProductId())){
                    idList.add(wmTask.getId());
                    ancestorTaskList.add(wmTask);
                }
            }
        }

        return ancestorTaskList;
    };

    @Override
    public List<WmTask> selectAncestorTaskList(List<WmTask> wmTaskList){
        List<String> idList = new ArrayList<>();
        List<WmTask> ancestorTaskList =  new ArrayList<>();
        for(WmTask wmTask: wmTaskList){
            List<String> ancestorIdList = Arrays.asList(wmTask.getAncestors().split(","));
            if(ancestorIdList.size() > 1) {
                //祖先是别人
                WmTask ancestorTask = getById(ancestorIdList.get(1));
                if(!idList.contains(ancestorTask.getId())){
                    idList.add(ancestorTask.getId());
                    ancestorTaskList.add(ancestorTask);
                }
            }
            else {
                //祖先是自己
                if(!idList.contains(wmTask.getId())){
                    idList.add(wmTask.getId());
                    ancestorTaskList.add(wmTask);
                }
            }
        }

        return ancestorTaskList;
    };

    @Override
    public WmTask selectTreeChildrenWithTask(WmTask wmTask){
        //1、通过任务书ID获取任务
        List<WmTask> wmTaskListChildren = queryTaskChildren(wmTask);
        wmTask.setChildren(wmTaskListChildren);
        wmTask.setKey(wmTask.getId());
        wmTask.setTitle(wmTask.getName());
        wmTask.setIsLeaf(wmTaskListChildren.isEmpty());
        if(!StringUtils.isEmpty(wmTask.getCurrentNodeId())) {
            SysDepartModel sysDepartModel = sysBaseApi.selectAllById(wmTask.getCurrentNodeId());
            wmTask.setCurrentNodeId_dictText(sysDepartModel.getDepartName());
        }
        return wmTask;
    };

    @Override
    public WmTask getRootTaskByWmTaskbookId(String wmTaskbookId){
        LambdaQueryWrapper<WmTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.likeRight(WmTask::getWmTaskbookId, wmTaskbookId).eq(WmTask::getAncestors, "0").last("LIMIT 1");
        WmTask wmTask = getOne(queryWrapper);
        return wmTask;
    };

    @Override
    public WmTask getRootTaskByWmTaskbookIdAndVersion(String wmTaskbookId, String version){
        LambdaQueryWrapper<WmTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.likeRight(WmTask::getWmTaskbookId, wmTaskbookId);
        if(version == null){
            queryWrapper.isNull(WmTask::getCurrentVersion);
        }
        else{
            queryWrapper.eq(WmTask::getCurrentVersion, version);
        }
        queryWrapper.eq(WmTask::getAncestors, UserConstant.ANCESTOR_ZERO);
        queryWrapper.last("LIMIT 1");
        WmTask wmTask = getOne(queryWrapper);
        return wmTask;
    };

    @Override
    public List<String> getExpandKeys(WmTask wmTask){
        List<String> keyList = new ArrayList<>();
        keyList.add(wmTask.getId());

        List<String> taskChildrenId = queryTaskChildrenId(wmTask);
        if(!taskChildrenId.isEmpty()){
            keyList.addAll(taskChildrenId);
        }
        return keyList;
    };

    /**
     * 递归获取任务子任务ID列表
     * @param wmTaskParent
     * @return
     */
    private List<String> queryTaskChildrenId(WmTask wmTaskParent){
        List<String> wmTaskIdListFinal = new ArrayList<>();
        if(wmTaskParent.getIsSendUnit().equals(UserConstant.SYS_NO)) {
            //循环到发货单位时，下面子任务不再往下获取
            LambdaQueryWrapper<WmTask> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(WmTask::getPid, wmTaskParent.getId());
            if(wmTaskParent.getCurrentVersion() == null){
                queryWrapper.isNull(WmTask::getCurrentVersion);
            }
            else{
                queryWrapper.eq(WmTask::getCurrentVersion, wmTaskParent.getCurrentVersion());
            }
            List<WmTask> wmTaskList = list(queryWrapper);
            for (WmTask wmTask : wmTaskList) {
                if(wmTask.getIsSendUnit().equals(UserConstant.SYS_NO)) {
                    wmTaskIdListFinal.add(wmTask.getId());
                }
                List<String> taskChildrenId = queryTaskChildrenId(wmTask);
                if (!taskChildrenId.isEmpty()) {
                    wmTaskIdListFinal.addAll(taskChildrenId);
                }
            }
        }

        return wmTaskIdListFinal;
    }

    @Override
    public List<WmTask> getChildrenAsOneList(WmTask wmTaskParent){
        List<WmTask> wmTaskListFinal = new ArrayList<>();
        wmTaskListFinal.add(wmTaskParent);
        List<WmTask> wmTaskList = queryTaskChildrenAsOneList(wmTaskParent);
        if(!wmTaskList.isEmpty()) {
            wmTaskListFinal.addAll(wmTaskList);
        }
        return wmTaskListFinal;
    };

    /**
     * 递归获取任务子任务列表(返回值在一个列表)
     * @param wmTaskParent
     * @return
     */
    private List<WmTask> queryTaskChildrenAsOneList(WmTask wmTaskParent){
        List<WmTask> wmTaskListFinal = new ArrayList<>();
        //1、如果是作为菜单树，只到发货单位为止，2、如果不是菜单树，遍历所有任务
        LambdaQueryWrapper<WmTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmTask::getPid, wmTaskParent.getId());
        if(wmTaskParent.getCurrentVersion() == null){
            queryWrapper.isNull(WmTask::getCurrentVersion);
        }
        else{
            queryWrapper.eq(WmTask::getCurrentVersion, wmTaskParent.getCurrentVersion());
        }
        List<WmTask> wmTaskList = list(queryWrapper);
        for (WmTask wmTask : wmTaskList) {
            List<WmTask> taskChildren = queryTaskChildrenAsOneList(wmTask);
            wmTask.setChildren(taskChildren);
            wmTask.setKey(wmTask.getId());
            wmTask.setParentId(wmTask.getPid());
            wmTask.setTitle(wmTask.getName());
            wmTask.setIsLeaf(taskChildren.isEmpty());
            if(!StringUtils.isEmpty(wmTask.getCurrentNodeId())) {
                SysDepartModel sysDepartModel = sysBaseApi.selectAllById(wmTask.getCurrentNodeId());
                wmTask.setCurrentNodeId_dictText(sysDepartModel.getDepartName());
            }

            wmTaskListFinal.add(wmTask);
            if(!taskChildren.isEmpty()) {
                wmTaskListFinal.addAll(taskChildren);
            }
        }

        return wmTaskListFinal;
    }

    /**
     * 通过合同产品查询根任务（生产任务书为设计起点任务，其他类型为根任务）
     */
    @Override
    public List<WmTask> selectRootTaskByContractProduct(List<String> wmContractProductList){
        LambdaQueryWrapper<WmTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(WmTask::getWmContractProductId, wmContractProductList).eq(WmTask::getAncestors, UserConstant.ANCESTOR_ZERO);
        List<WmTask> wmTaskList = list(queryWrapper);

        return wmTaskList;
    };

    @Override
    public List<WmTask> selectStatisticTaskByContractProduct(List<String> wmContractProductList){
        List<WmTask> wmTaskList = new ArrayList<>();
        //生产任务书类型
        List<String> produceTypeList = new ArrayList<>();
        produceTypeList.add(UserConstant.TASKBOOK_TYPE_PRODUCE);
        produceTypeList.add(UserConstant.TASKBOOK_TYPE_PRODUCE_ELECTRIC);
        //非生产任务书任务（所有根任务）,生产任务书任务(所有设计起点任务)
        LambdaQueryWrapper<WmTask> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.in(WmTask::getWmContractProductId, wmContractProductList).eq(WmTask::getAncestors, UserConstant.ANCESTOR_ZERO).notIn(WmTask::getTaskbookType, produceTypeList);
        List<WmTask> wmTaskListNoProduce = list(queryWrapper1);
        wmTaskList.addAll(wmTaskListNoProduce);

        LambdaQueryWrapper<WmTask> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.in(WmTask::getWmContractProductId, wmContractProductList).eq(WmTask::getIsStartPoint, UserConstant.SYS_YES).in(WmTask::getTaskbookType, produceTypeList);
        List<WmTask> wmTaskListProduce = list(queryWrapper2);
        wmTaskList.addAll(wmTaskListProduce);

        return wmTaskList;
    };

    /**
     * 通过合同产品查询留存任务（生产任务书为设计起点任务，其他类型为根任务）
     */
    @Override
    public List<WmTask> selectRemainTaskByContractProduct(List<String> wmContractProductList){
        List<String> notProduceTaskbookType = new ArrayList<>();
        notProduceTaskbookType.add(UserConstant.TASKBOOK_TYPE_DESIGN);
        notProduceTaskbookType.add(UserConstant.TASKBOOK_TYPE_TECHNOLOGY);
        notProduceTaskbookType.add(UserConstant.TASKBOOK_TYPE_PURCHASE);
        notProduceTaskbookType.add(UserConstant.TASKBOOK_TYPE_DEBUG);
        notProduceTaskbookType.add(UserConstant.TASKBOOK_TYPE_PROCESS);
        List<WmTask> wmTaskList = new ArrayList<>();

        //非生产任务书任务（所有根任务）
        LambdaQueryWrapper<WmTask> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.in(WmTask::getWmContractProductId, wmContractProductList).eq(WmTask::getAncestors, UserConstant.ANCESTOR_ZERO).in(WmTask::getTaskbookType, notProduceTaskbookType);
        List<WmTask> wmTaskListOfNotProduce = list(queryWrapper1);
        wmTaskList.addAll(wmTaskListOfNotProduce);

        //生产任务书任务(所有设计起点任务)
        LambdaQueryWrapper<WmTask> queryWrapper2 = new LambdaQueryWrapper<>();
        //生产任务书类型
        List<String> produceTypeList = new ArrayList<>();
        produceTypeList.add(UserConstant.TASKBOOK_TYPE_PRODUCE);
        produceTypeList.add(UserConstant.TASKBOOK_TYPE_PRODUCE_ELECTRIC);
        queryWrapper2.in(WmTask::getWmContractProductId, wmContractProductList).eq(WmTask::getIsStartPoint, UserConstant.SYS_YES).in(WmTask::getTaskbookType, produceTypeList);
        List<WmTask> wmTaskListOfProduce = list(queryWrapper2);
        wmTaskList.addAll(wmTaskListOfProduce);

        return wmTaskList;
    };

    @Override
    public WmProjectStatisticVo getStatisticByContractProduct(List<String> wmContractProductList){
        List<WmTask> wmTaskList = selectStatisticTaskByContractProduct(wmContractProductList);
        Integer notStartTaskNum = 0;  //未开始的任务数量
        Integer doingTaskNum = 0;     //进行中的任务数量
        Integer completedTaskNum = 0; //已完成的任务数量
        for(WmTask wmTask: wmTaskList){
            //生产任务书类型
            List<String> produceTypeList = new ArrayList<>();
            produceTypeList.add(UserConstant.TASKBOOK_TYPE_PRODUCE);
            produceTypeList.add(UserConstant.TASKBOOK_TYPE_PRODUCE_ELECTRIC);

            //非生产任务书任务（所有根任务）,生产任务书任务(所有设计起点任务)
            if((produceTypeList.contains(wmTask.getTaskbookType()) && wmTask.getIsStartPoint().equals(UserConstant.SYS_YES)) || (!produceTypeList.contains(wmTask.getTaskbookType()) && wmTask.getAncestors().equals(UserConstant.ANCESTOR_ZERO))) {
                List<String> notStartStatusList = new ArrayList<>();
                notStartStatusList.add(UserConstant.TASK_STATUS_PREPARE);
                //notStartStatusList.add(UserConstant.TASK_STATUS_PLAN_APPROVED);
                notStartStatusList.add(UserConstant.TASK_STATUS_TECHNOLOGY_UNAPPROVED);
                notStartStatusList.add(UserConstant.TASK_STATUS_PRODUCE_UNAPPROVED);
                if (notStartStatusList.contains(wmTask.getStatus())) {
                    notStartTaskNum++;
                } else if (wmTask.getStatus().equals(UserConstant.TASK_STATUS_FINISHED)) {
                    completedTaskNum++;
                } else {
                    doingTaskNum++;
                }
            }
        }

        WmProjectStatisticVo wmProjectStatisticVo = new WmProjectStatisticVo();
        wmProjectStatisticVo.setCompletedTaskNum(completedTaskNum);
        wmProjectStatisticVo.setDoingTaskNum(doingTaskNum);
        wmProjectStatisticVo.setNotStartTaskNum(notStartTaskNum);
        return wmProjectStatisticVo;
    };

    @Override
    public List<WmTask> selectRemainTaskRankByContractProduct(List<String> wmContractProductList){
        //留存任务列表（生产任务书为设计起点任务，其他类型为根任务）
        List<WmTask> wmTaskList = selectRemainTaskByContractProduct(wmContractProductList);
        List<WmTask> wmTaskListNew = new ArrayList<>();
        for(WmTask wmTask: wmTaskList){
            //获取任务所花时间，如结束时间为空，结束时间算当前时间
            Integer useDayNum = WmhbUtil.countDiffDay(wmTask.getFactBeginTime(), wmTask.getFactEndTime());
            wmTask.setUseDayNum(useDayNum);
            String dictText = sysDictService.queryDictTextByKey(UserConstant.TASKBOOK_TYPE, wmTask.getTaskbookType());
            wmTask.setTaskbookType_dictText(dictText);
            wmTaskListNew.add(wmTask);
        }

        //排序求出排名前十的任务
        List<WmTask> wmTaskListRank = bubbleSort(wmTaskListNew);

        return wmTaskListRank;
    };

    @Override
    public List<WmTask> selectTaskByContractProduct(List<String> wmContractProductList){
        LambdaQueryWrapper<WmTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(WmTask::getWmContractProductId, wmContractProductList);
        List<WmTask> wmTaskList = list(queryWrapper);
        return wmTaskList;
    };

    @Override
    public List<WmTask> selectSendUnitTask(List<String> wmContractProductList, String firstDayOfMonth, String lastDayOfMonth){
        List<WmTask> wmTaskList = baseMapper.selectSendUnitTask(wmContractProductList, firstDayOfMonth, lastDayOfMonth, UserConstant.SYS_YES, UserConstant.TASKBOOK_TYPE_PRODUCE);
        return wmTaskList;
    };

    @Override
    public List<WmTask> selectPurchaseTask(List<String> wmContractProductList){
        LambdaQueryWrapper<WmTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(WmTask::getWmContractProductId, wmContractProductList).eq(WmTask::getIsStartPoint, UserConstant.SYS_YES).eq(WmTask::getTaskbookType, UserConstant.TASKBOOK_TYPE_PURCHASE);
        List<WmTask> wmTaskList = list(queryWrapper);
        return wmTaskList;
    };

    /**
     * 列表冒泡排序
     * @param wmTaskList
     * @return
     */
    private List<WmTask> bubbleSort(List<WmTask> wmTaskList){
        if(wmTaskList.isEmpty()){
            return wmTaskList;
        }

        for (int i = 0; i < wmTaskList.size() - 1; i++) {
            for (int j = 0; j < wmTaskList.size() - i - 1; j++) {
                if (wmTaskList.get(j).getUseDayNum() < wmTaskList.get(j + 1).getUseDayNum()) {
                    Collections.swap(wmTaskList, j, j + 1);
                }
            }
        }

        return wmTaskList.subList(0, Math.min(20, wmTaskList.size()));//截取前二十条
    }

    @Override
    public List<WmDepartRemainTaskVo> remainList(String buId, List<String> contractProductIdList, List<String> buDepartList){
        List<WmDepartRemainTaskVo> wmDepartRemainTaskVoList = new ArrayList<>();
        //1、查询事业部下所有涉及到的部门列表
        for(String departId: buDepartList) {
            WmDepartRemainTaskVo wmDepartRemainTaskVo = new WmDepartRemainTaskVo();
            SysDepartModel sysDepartModel = sysBaseApi.selectAllById(departId);
            List<WmTask> wmTaskList = baseMapper.selectBuDepartRemainTask(buId, contractProductIdList, departId);
            List<WmTask> wmTaskListNew = new ArrayList<>();
            for(WmTask wmTask: wmTaskList){
                //生产任务书类型
                List<String> produceTypeList = new ArrayList<>();
                produceTypeList.add(UserConstant.TASKBOOK_TYPE_PRODUCE);
                produceTypeList.add(UserConstant.TASKBOOK_TYPE_PRODUCE_ELECTRIC);

                String TaskbookTypeDictText = sysDictService.queryDictTextByKey(UserConstant.TASKBOOK_TYPE, wmTask.getTaskbookType());
                String statusDictText = sysDictService.queryDictTextByKey(UserConstant.TASK_STATUS, wmTask.getStatus());
                wmTask.setTaskbookType_dictText(TaskbookTypeDictText);
                wmTask.setStatus_dictText(statusDictText);

                //非生产任务书任务（所有根任务）,生产任务书任务(所有设计起点任务)
                if((produceTypeList.contains(wmTask.getTaskbookType()) && wmTask.getIsStartPoint().equals(UserConstant.SYS_YES)) || (!produceTypeList.contains(wmTask.getTaskbookType()) && wmTask.getAncestors().equals(UserConstant.ANCESTOR_ZERO))) {
                    Date beginDate = wmTask.getPlanBeginTime();
                    if(!wmTask.getCurrentNodeIndex().equals(0)){
                        //如果当前部门不是第一个时，获取上一流程时间数据
                        WmTaskFlow wmTaskFlowPrev = wmTaskFlowService.getByTaskAndIndex(wmTask.getId(), wmTask.getCurrentNodeIndex()-1);
                        beginDate = wmTaskFlowPrev.getFinishTime();
                    }
                    WmTaskFlow wmTaskFlowCurr = wmTaskFlowService.getByTaskAndIndex(wmTask.getId(), wmTask.getCurrentNodeIndex());
                    Integer needDayNum = WmhbUtil.countDiffDay(beginDate, wmTaskFlowCurr.getFinishTime());
                    wmTask.setNeedDayNum(needDayNum);
                    wmTask.setDepPlanBeginTime(beginDate);
                    wmTask.setDepPlanEndTime(wmTaskFlowCurr.getFinishTime());
                    if(wmTask.getFactEndTime() != null){
                        //如果任务已结束，则当前节点完成时间为任务结束时间，否则否空
                        wmTask.setCurrentNodeEndTime(wmTask.getFactEndTime());
                    }
                    wmTask.setUseDayNum(WmhbUtil.countDiffDay(wmTask.getCurrentNodeTime(), wmTask.getCurrentNodeEndTime()));//停留时间
                    Integer diffDays = wmTask.getNeedDayNum() - wmTask.getUseDayNum();
                    if (diffDays >= 0) {
                        wmTask.setColor("#67c23a");
                    } else if (diffDays < -10) {
                        wmTask.setColor("#f56c6c");
                    } else {
                        wmTask.setColor("#e6a23c");
                    }
                    wmTaskListNew.add(wmTask);
                }
            }
            wmDepartRemainTaskVo.setWmTaskList(wmTaskListNew);
            wmDepartRemainTaskVo.setDepartId(sysDepartModel.getId());
            wmDepartRemainTaskVo.setDepartName(sysDepartModel.getDepartName());
            wmDepartRemainTaskVoList.add(wmDepartRemainTaskVo);
        }

        return wmDepartRemainTaskVoList;
    };

    @Override
    public Boolean produceTaskHasSendUnit(String wmTaskbookId){
        //生产任务书类型
        List<String> produceTypeList = new ArrayList<>();
        produceTypeList.add(UserConstant.TASKBOOK_TYPE_PRODUCE);
        produceTypeList.add(UserConstant.TASKBOOK_TYPE_PRODUCE_ELECTRIC);

        LambdaQueryWrapper<WmTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmTask::getIsSendUnit, UserConstant.SYS_YES).eq(WmTask::getWmTaskbookId, wmTaskbookId).in(WmTask::getTaskbookType, produceTypeList);
        List<WmTask> wmTaskList = list(queryWrapper);
        return !wmTaskList.isEmpty();
    };

    @Override
    public List<WmProductRecpt> selectStartPointTask(List<String> wmContractProductList, String firstDayOfMonth, String lastDayOfMonth){
        List<WmProductRecpt> wmProductRecptList = new ArrayList<>();
        List<String> idList = new ArrayList<>();
        List<WmProductRecpt> productRecptList = baseMapper.selectStartPointTask(wmContractProductList, firstDayOfMonth, lastDayOfMonth, UserConstant.SYS_YES, UserConstant.TASKBOOK_TYPE_PRODUCE);
        for(WmProductRecpt wmProductRecpt: productRecptList){
            //只取最新入库的数据
            if(!idList.contains(wmProductRecpt.getWmTaskId())){
                idList.add(wmProductRecpt.getWmTaskId());
                wmProductRecptList.add(wmProductRecpt);
            }
        }
        return wmProductRecptList;
    }

    @Override
    public List<WmOutSource> selectOutSourceTask(List<String> wmContractProductList, String firstDayOfMonth, String lastDayOfMonth){
        List<WmOutSource> wmOutSourceList = new ArrayList<>();
        List<String> idList = new ArrayList<>();
        List<WmOutSource> outSourceList = baseMapper.selectOutSourceTask(wmContractProductList, firstDayOfMonth, lastDayOfMonth, UserConstant.TASK_TYPE_OUT, UserConstant.TASKBOOK_TYPE_PRODUCE);
        for(WmOutSource wmOutSource: outSourceList){
            //只取最新外协的数据
            if(!idList.contains(wmOutSource.getWmTaskId())){
                idList.add(wmOutSource.getWmTaskId());
                wmOutSourceList.add(wmOutSource);
            }
        }
        return wmOutSourceList;
    };

    @Override
    public List<WmProductDebug> selectInstallDebugTask(List<String> wmContractProductList, String firstDayOfMonth, String lastDayOfMonth){
        List<WmProductDebug> wmProductDebugList = new ArrayList<>();
        List<String> idList = new ArrayList<>();
        List<WmProductDebug> productDebugList = baseMapper.selectInstallDebugTask(wmContractProductList, firstDayOfMonth, lastDayOfMonth);
        for(WmProductDebug wmProductDebug: productDebugList){
            //只取最新外协的数据
            if(!idList.contains(wmProductDebug.getWmTaskId())){
                idList.add(wmProductDebug.getWmTaskId());
                wmProductDebugList.add(wmProductDebug);
            }
        }
        return wmProductDebugList;
    };

    @Override
    public List<WmTask> sameLevelTask(WmTask wmTask){
        LambdaQueryWrapper<WmTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmTask::getAncestors, wmTask.getAncestors());
        if(wmTask.getCurrentVersion() == null){
            queryWrapper.isNull(WmTask::getCurrentVersion);
        }
        else{
            queryWrapper.eq(WmTask::getCurrentVersion, wmTask.getCurrentVersion());
        }
        List<WmTask> wmTaskList = list(queryWrapper);
        return wmTaskList;
    };

    @Override
    public List<WmTask> startPointTask(String wmTaskbookId){
        LambdaQueryWrapper<WmTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmTask::getWmTaskbookId, wmTaskbookId).eq(WmTask::getIsStartPoint, UserConstant.SYS_YES);
        List<WmTask> wmTaskList = list(queryWrapper);
        return wmTaskList;
    };

    @Override
    public List<WmTask> ancestorTask(WmTask wmTask){
        List<WmTask> wmTaskList = new ArrayList<>();
        List<String> ancestorList = Arrays.asList(wmTask.getAncestors().split(","));
        for(String id: ancestorList){
            if(!id.equals("0")){
                WmTask wmTaskItem = getById(id);
                wmTaskList.add(wmTaskItem);
            }
        }

        return wmTaskList;
    };

    @Override
    public List<WmTask> searchByName(String searchKey){
        //生产任务书类型
        List<String> produceTypeList = new ArrayList<>();
        produceTypeList.add(UserConstant.TASKBOOK_TYPE_PRODUCE);
        produceTypeList.add(UserConstant.TASKBOOK_TYPE_PRODUCE_ELECTRIC);

        List<WmTask> wmTaskList = new ArrayList<>();
        LambdaQueryWrapper<WmTask> queryWrapperProduce = new LambdaQueryWrapper<>();
        queryWrapperProduce.like(WmTask::getName, searchKey)
                .in(WmTask::getTaskbookType, produceTypeList)
                .eq(WmTask::getIsStartPoint, UserConstant.SYS_YES);
        List<WmTask> wmTaskListProduce = list(queryWrapperProduce);
        wmTaskList.addAll(wmTaskListProduce);

        LambdaQueryWrapper<WmTask> queryWrapperNotProduce = new LambdaQueryWrapper<>();
        queryWrapperNotProduce.like(WmTask::getName, searchKey)
                .notIn(WmTask::getTaskbookType, produceTypeList)
                .eq(WmTask::getAncestors, UserConstant.ANCESTOR_ZERO);
        List<WmTask> wmTaskListNotProduce = list(queryWrapperNotProduce);
        wmTaskList.addAll(wmTaskListNotProduce);
        return wmTaskList;
    };

    @Override
    public List<WmTask> selectTaskChildrenUntilSendUnit(WmTask wmTask){
        List<WmTask> wmTaskList = queryTaskChildrenUntilSendUnit(wmTask);
        return wmTaskList;
    };

    /**
     * 递归获取任务子任务列表,只到发货单位为止
     * @param wmTaskParent
     * @return
     */
    private List<WmTask> queryTaskChildrenUntilSendUnit(WmTask wmTaskParent){
        List<WmTask> wmTaskListFinal = new ArrayList<>();
        LambdaQueryWrapper<WmTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmTask::getPid, wmTaskParent.getId());
        if(wmTaskParent.getCurrentVersion() == null){
            queryWrapper.isNull(WmTask::getCurrentVersion);
        }
        else{
            queryWrapper.eq(WmTask::getCurrentVersion, wmTaskParent.getCurrentVersion());
        }
        List<WmTask> wmTaskList = list(queryWrapper);
        for (WmTask wmTask : wmTaskList) {
            wmTask.setWmTaskbook(wmTaskParent.getWmTaskbook());
            wmTask.setTaskbookStatus(wmTaskParent.getTaskbookStatus());
            if(!wmTask.getIsSendUnit().equals(UserConstant.SYS_YES)) {
                //当前任务如果不是发货单位，一直往下求其子任务列表，是的话跳过求子任务列表
                List<WmTask> taskChildren = queryTaskChildrenUntilSendUnit(wmTask);
                wmTask.setChildren(taskChildren);
                wmTask.setIsLeaf(taskChildren.isEmpty());
            }
            else{
                wmTask.setIsLeaf(true);
            }

            wmTask.setKey(wmTask.getId());
            wmTask.setParentId(wmTask.getPid());
            wmTask.setTitle(wmTask.getName());

            if(!StringUtils.isEmpty(wmTask.getCurrentNodeId())) {
                SysDepartModel sysDepartModel = sysBaseApi.selectAllById(wmTask.getCurrentNodeId());
                wmTask.setCurrentNodeId_dictText(sysDepartModel.getDepartName());
            }
            wmTaskListFinal.add(wmTask);
        }

        return wmTaskListFinal;
    }

    @Override
    public List<WmTask> selectTaskIdOfDesignList(String taskbookType, String status, List<String> contractProductIdList){
        List<WmTask> wmTaskList = new ArrayList<>();
        if(!contractProductIdList.isEmpty()) {
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            LambdaQueryWrapper<WmTask> queryWrapper = new LambdaQueryWrapper<>();
            //非管理员和没有角色须是指派人员
            Set<String> roles = sysUserService.getUserRoleSetById(sysUser.getId());
            if(roles.isEmpty() || !roles.contains("admin")) {
                queryWrapper.eq(WmTask::getDesignUserId, sysUser.getId());
            }
            queryWrapper.in(WmTask::getWmContractProductId, contractProductIdList);

            //如果是采购任务，根据状态参数查询数据
            if (taskbookType.contains(UserConstant.TASKBOOK_TYPE_PURCHASE)) {
                List<String> waitPurchaseList = new ArrayList<>();
                waitPurchaseList.add(UserConstant.TASK_STATUS_WAIT_PURCHASE);
                waitPurchaseList.add(UserConstant.TASK_STATUS_PURCHASE_APPROVED);
                if(!StringUtils.isEmpty(status)) {
                    if (status.equals(UserConstant.TASK_STATUS_WAIT_PURCHASE)) {
                        //待采购
                        queryWrapper.in(WmTask::getStatus, waitPurchaseList);
                    }
                    else if (status.equals(UserConstant.TASK_STATUS_PURCHASED)) {
                        //已采购
                        queryWrapper.notIn(WmTask::getStatus, waitPurchaseList);
                    }
                }
            }
            queryWrapper.orderByDesc(WmTask::getCreateTime);
            wmTaskList = list(queryWrapper);
        }
        return wmTaskList;
    };

    @Override
    public List<WmTask> selectTaskOfDebugList(List<String> contractProductIdList){
        List<WmTask> wmTaskList = new ArrayList<>();
        if(!contractProductIdList.isEmpty()) {
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            LambdaQueryWrapper<WmTask> queryWrapper = new LambdaQueryWrapper<>();
            //非管理员和没有角色须是指派人员
            Set<String> roles = sysUserService.getUserRoleSetById(sysUser.getId());
            if(roles.isEmpty() || !roles.contains("admin")) {
                queryWrapper.eq(WmTask::getDebugUserId, sysUser.getId());
            }

            queryWrapper.in(WmTask::getWmContractProductId, contractProductIdList);

            wmTaskList = list(queryWrapper);
        }
        return wmTaskList;
    };

    @Override
    public List<WmTask> selectTaskOfProcessList(String taskbookType, String status, List<String> contractProductIdList){
        List<WmTask> wmTaskList = new ArrayList<>();
        if(!contractProductIdList.isEmpty()) {
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            LambdaQueryWrapper<WmTask> queryWrapper = new LambdaQueryWrapper<>();
            //非管理员和没有角色须是指派人员
            Set<String> roles = sysUserService.getUserRoleSetById(sysUser.getId());
            if(roles.isEmpty() || !roles.contains("admin")) {
                queryWrapper.eq(WmTask::getProcessUserId, sysUser.getId());
            }
            queryWrapper.in(WmTask::getWmContractProductId, contractProductIdList);

            //如果是采购任务，根据状态参数查询数据
            if (!StringUtils.isEmpty(status) && taskbookType.contains(UserConstant.TASKBOOK_TYPE_PURCHASE)) {
                //采购任务
                if (status.equals(UserConstant.TASK_STATUS_WAIT_PURCHASE)) {
                    //待采购
                    queryWrapper.eq(WmTask::getStatus, UserConstant.TASK_STATUS_WAIT_PURCHASE);
                } else {
                    //已采购
                    queryWrapper.ne(WmTask::getStatus, UserConstant.TASK_STATUS_WAIT_PURCHASE);
                }
            }

            wmTaskList = list(queryWrapper);
        }
        return wmTaskList;
    };

    @Override
    public Boolean isProcessSubmit(String wmTaskbookId){
        LambdaQueryWrapper<WmTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmTask::getWmTaskbookId, wmTaskbookId).eq(WmTask::getIsStartPoint, UserConstant.SYS_YES).eq(WmTask::getHasChild, UserConstant.HAS_CHILD_YES);
        List<WmTask> wmTaskList = list(queryWrapper);
        return !wmTaskList.isEmpty();
    };

    @Override
    public List<WmTask> selectTaskOfEngineerList(List<String> contractProductIdList){
        List<WmTask> wmTaskList = new ArrayList<>();
        if(!contractProductIdList.isEmpty()) {
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            LambdaQueryWrapper<WmTask> queryWrapper = new LambdaQueryWrapper<>();
            //非管理员和没有角色须是指派人员
            Set<String> roles = sysUserService.getUserRoleSetById(sysUser.getId());
            if(roles.isEmpty() || !roles.contains("admin")) {
                queryWrapper.eq(WmTask::getStorageUserId, sysUser.getId());
            }
            queryWrapper.eq(WmTask::getTaskbookType, UserConstant.TASKBOOK_TYPE_DEBUG);
            queryWrapper.in(WmTask::getWmContractProductId, contractProductIdList);

            wmTaskList = list(queryWrapper);
        }
        return wmTaskList;
    };

    @Override
    public List<WmTask> shouldSendList(List<String> contractProductIdList){
        List<WmTask> wmTaskList = new ArrayList<>();
        if(!contractProductIdList.isEmpty()) {
            LambdaQueryWrapper<WmTask> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(WmTask::getWmContractProductId, contractProductIdList);
            //所有应发货物清单
            queryWrapper.eq(WmTask::getIsSendUnit, UserConstant.SYS_YES); //发货级
            wmTaskList = list(queryWrapper);
        }
        return wmTaskList;
    };

    @Override
    public List<WmTask> produceProduceSendList(List<String> contractProductIdList){
        List<WmTask> wmTaskList = new ArrayList<>();
        if(!contractProductIdList.isEmpty()) {
            LambdaQueryWrapper<WmTask> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(WmTask::getWmContractProductId, contractProductIdList);
            //自制产品（半成品）
            queryWrapper.eq(WmTask::getIsSendUnit, UserConstant.SYS_YES);            //发货级
            queryWrapper.eq(WmTask::getType, UserConstant.TASK_TYPE_SELF);           //自制品
            queryWrapper.eq(WmTask::getItemOrProduct, UserConstant.PRODUCT_PRODUCT); //产品
            wmTaskList = list(queryWrapper);
        }
        return wmTaskList;
    };

    @Override
    public List<WmTask> purchaseMaterialSendList(List<String> contractProductIdList){
        List<WmTask> wmTaskList = new ArrayList<>();
        if(!contractProductIdList.isEmpty()) {
            LambdaQueryWrapper<WmTask> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(WmTask::getWmContractProductId, contractProductIdList);
            //外购物料（外购的物料）
            queryWrapper.eq(WmTask::getIsSendUnit, UserConstant.SYS_YES);            //发货级
            queryWrapper.eq(WmTask::getType, UserConstant.TASK_TYPE_BUY);            //外购
            queryWrapper.eq(WmTask::getItemOrProduct, UserConstant.PRODUCT_ITEM);    //物料
            wmTaskList = list(queryWrapper);
        }
        return wmTaskList;
    };

    @Override
    public List<WmTask> purchaseProductSendList(List<String> contractProductIdList){
        List<WmTask> wmTaskList = new ArrayList<>();
        if(!contractProductIdList.isEmpty()) {
            LambdaQueryWrapper<WmTask> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(WmTask::getWmContractProductId, contractProductIdList);
            //外购件（外购的产品）
            queryWrapper.eq(WmTask::getIsSendUnit, UserConstant.SYS_YES);            //发货级
            queryWrapper.eq(WmTask::getType, UserConstant.TASK_TYPE_BUY);            //外购
            queryWrapper.eq(WmTask::getItemOrProduct, UserConstant.PRODUCT_PRODUCT); //物料
            wmTaskList = list(queryWrapper);
        }
        return wmTaskList;
    };

    @Override
    public List<WmTask> listByContractProductList(List<WmContractProduct> wmContractProductList){
        List<String> wmContractProductIdList = new ArrayList<>();
        for(WmContractProduct wmContractProduct: wmContractProductList){
            wmContractProductIdList.add(wmContractProduct.getId());
        }

        //生产任务书类型
        List<String> produceTypeList = new ArrayList<>();
        produceTypeList.add(UserConstant.TASKBOOK_TYPE_PRODUCE);
        produceTypeList.add(UserConstant.TASKBOOK_TYPE_PRODUCE_ELECTRIC);

        List<WmTask> wmTaskList = new ArrayList<>();
        if(!wmContractProductIdList.isEmpty()) {
            LambdaQueryWrapper<WmTask> queryWrapperProduce = new LambdaQueryWrapper<>();
            queryWrapperProduce.in(WmTask::getWmContractProductId, wmContractProductIdList)
                    .in(WmTask::getTaskbookType, produceTypeList)
                    .eq(WmTask::getIsStartPoint, UserConstant.SYS_YES);
            List<WmTask> wmTaskListProduce = list(queryWrapperProduce);
            wmTaskList.addAll(wmTaskListProduce);

            LambdaQueryWrapper<WmTask> queryWrapperNotProduce = new LambdaQueryWrapper<>();
            queryWrapperNotProduce.in(WmTask::getWmContractProductId, wmContractProductIdList)
                    .notIn(WmTask::getTaskbookType, produceTypeList)
                    .eq(WmTask::getAncestors, UserConstant.ANCESTOR_ZERO);
            List<WmTask> wmTaskListNotProduce = list(queryWrapperNotProduce);
            wmTaskList.addAll(wmTaskListNotProduce);
        }
        return wmTaskList;
    };

    @Override
    public void deleteByTaskbookId(String wmTaskbookId){
        baseMapper.deleteByTaskbookId(wmTaskbookId);
    };

    @Override
    public void addWmTaskByVersion(WmTask wmTask) {
        //新增时设置hasChild为0
        wmTask.setHasChild(IWmTaskService.NOCHILD);
        if(oConvertUtils.isEmpty(wmTask.getPid())){
            wmTask.setPid(IWmTaskService.ROOT_PID_VALUE);
            wmTask.setAncestors(IWmTaskService.ANCESTORS);
        }else{
            //如果当前节点父ID不为空 则设置父节点的hasChildren 为1
            WmTask parent = baseMapper.selectById(wmTask.getPid());
            if(parent!=null && !"1".equals(parent.getHasChild())){
                parent.setHasChild("1");
                baseMapper.updateById(parent);
            }

            if(parent != null) {
                wmTask.setAncestors(parent.getAncestors() + "," + parent.getId());
            }
        }
        baseMapper.insert(wmTask);
    }

    @Override
    public List<WmTask> submitSkillChange(WmTask wmTaskOfDesign, WmTaskbook wmTaskbookOfProduce){
        List<WmTask> wmTaskListNew = new ArrayList<>();

        //新版本设计BOM任务列表
        List<WmTask> wmTaskListNextVersion = queryTaskChildrenAsOneList(wmTaskOfDesign);

        //将新版本设计BOM任务转换为生产任务
        for(WmTask wmTask: wmTaskListNextVersion){
            //通过设计任务转换新的任务
            List<WmTask> wmTasks = generateSkillChange(wmTaskbookOfProduce, wmTask);
            wmTaskListNew.addAll(wmTasks);
        }

        //复制任务BOM
        WmTask rootProduceTaskOfNextVersion = getRootTaskByWmTaskbookIdAndVersion(wmTaskbookOfProduce.getId(), wmTaskbookOfProduce.getCurrentVersion());
        copyTaskBomSkillChange(wmTaskOfDesign, rootProduceTaskOfNextVersion);

        return wmTaskListNew;
    };

    /**
     * 从其他任务书的任务转换为新任务书的任务  参数为新任务书和原有任务
     * @param wmTaskbookOfProduce
     * @param wmTaskOfDesign
     */
    private List<WmTask> generateSkillChange(WmTaskbook wmTaskbookOfProduce, WmTask wmTaskOfDesign){
        List<WmTask> wmTaskListNew = new ArrayList<>();
        List<String> ancestorList = Arrays.asList(wmTaskOfDesign.getAncestors().split(","));
        WmTask wmTaskParentNew = new WmTask();
        //祖先节点循环复制
        for(String ancestor: ancestorList){
            //去除ID为0
            if(!StringUtils.isEmpty(ancestor) && !ancestor.equals("0")){
                //判断任务是否存在
                WmTask wmTaskAncestor = getById(ancestor);//祖先任务
                //复制祖先节点并保存为新节点，存在则不能新生成
                WmTask wmTask = findTaskOfTaskbookSkillChange(ancestor, wmTaskbookOfProduce.getId(), wmTaskbookOfProduce.getCurrentVersion());
                if(wmTask == null) {
                    wmTaskParentNew = copyTaskToSaveSkillChange(wmTaskbookOfProduce, wmTaskAncestor, wmTaskParentNew);
                    wmTaskListNew.add(wmTaskParentNew);
                }
                else{
                    BeanUtils.copyProperties(wmTask, wmTaskParentNew);
                }
            }
        }

        //复制叶子节点(从当前任务的ancestors链条看，任务本身为叶子节点)并保存为新节点，存在则不能新生成
        WmTask wmTask = findTaskOfTaskbookSkillChange(wmTaskOfDesign.getId(), wmTaskbookOfProduce.getId(), wmTaskbookOfProduce.getCurrentVersion());
        if(wmTask == null) {
            if(!StringUtils.isEmpty(wmTaskOfDesign.getIsStartPoint()) && wmTaskOfDesign.getIsStartPoint().equals(UserConstant.SYS_YES)){
                wmTaskOfDesign.setIsStartPoint(UserConstant.SYS_YES);
            }
            else{
                wmTaskOfDesign.setIsStartPoint(UserConstant.SYS_NO);
            }
            WmTask leafTask = copyTaskToSaveSkillChange(wmTaskbookOfProduce, wmTaskOfDesign, wmTaskParentNew);
            wmTaskListNew.add(leafTask);
        }

        return wmTaskListNew;
    }

    //查询任务书中的某名称的任务是否存在
    private WmTask findTaskOfTaskbookSkillChange(String wmTaskId, String wmTaskbookId, String currentVersion){
        //判断任务是否存在
        WmTask wmTask = getById(wmTaskId);//原始设计任务
        LambdaQueryWrapper<WmTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmTask::getName, wmTask.getName())
                .eq(WmTask::getWmTaskbookId, wmTaskbookId)
                .eq(WmTask::getCurrentVersion, currentVersion)
                .last("LIMIT 1"); //同一产品同一事业部下的同一类型任务书只能有一个
        WmTask wmTaskExist = getOne(queryWrapper);
        if(wmTaskExist != null){
            return wmTaskExist;
        }
        else{
            return null;
        }
    }

    //拷贝设计任务书的任务到新的任务书任务
    private WmTask copyTaskToSaveSkillChange(WmTaskbook wmTaskbook, WmTask wmTaskOriginal, WmTask wmTaskParentNew){
        WmTask wmTaskNew = new WmTask();
        wmTaskNew.setName(wmTaskOriginal.getName());
        wmTaskNew.setWmTaskbookId(wmTaskbook.getId());
        wmTaskNew.setCode(wmTaskOriginal.getCode());
        wmTaskNew.setWmContractProductId(wmTaskOriginal.getWmContractProductId());
        wmTaskNew.setWmItemId(wmTaskOriginal.getWmItemId());
        wmTaskNew.setTaskbookType(UserConstant.TASKBOOK_TYPE_PRODUCE);
        wmTaskNew.setEnableFlag(UserConstant.ENABLE_FLAG_YES);
        wmTaskNew.setTenantId(wmTaskOriginal.getTenantId());
        wmTaskNew.setSysOrgCode(wmTaskOriginal.getSysOrgCode());
        wmTaskNew.setItemOrProduct(wmTaskOriginal.getItemOrProduct());
        wmTaskNew.setUnitOfMeasure(wmTaskOriginal.getUnitOfMeasure());
        wmTaskNew.setQuantity(wmTaskOriginal.getQuantity());
        wmTaskNew.setCanEditFlow(wmTaskOriginal.getCanEditFlow());
        wmTaskNew.setIsSendUnit(wmTaskOriginal.getIsSendUnit());
        wmTaskNew.setSpecification(wmTaskOriginal.getSpecification());
        wmTaskNew.setDesignFile(wmTaskOriginal.getDesignFile());
        wmTaskNew.setBuId(wmTaskbook.getBuId());
        wmTaskNew.setItemType(wmTaskOriginal.getItemType());
        wmTaskNew.setDesignUserId(wmTaskOriginal.getDesignUserId());
        wmTaskNew.setProcessUserId(wmTaskOriginal.getProcessUserId());
        wmTaskNew.setCurrentVersion(wmTaskbook.getCurrentVersion());

        if(!StringUtils.isEmpty(wmTaskOriginal.getType())) {
            wmTaskNew.setType(wmTaskOriginal.getType());
        }
        else{
            wmTaskNew.setType(UserConstant.TASK_TYPE_SELF);
        }

        if(!StringUtils.isEmpty(wmTaskParentNew.getId())){
            wmTaskNew.setPid(wmTaskParentNew.getId());
            wmTaskNew.setAncestors(wmTaskParentNew.getAncestors() + "," + wmTaskParentNew.getId());
            if(!StringUtils.isEmpty(wmTaskParentNew.getIsStartPoint()) && wmTaskParentNew.getIsStartPoint().equals(UserConstant.SYS_YES)) {
                //如果父任务是设计起点任务，则任务的报料任务ID为父任务ID
                wmTaskNew.setOrderTaskId(wmTaskParentNew.getId());
            }
            if (!StringUtils.isEmpty(wmTaskParentNew.getOrderTaskId())) {
                //如果父任务的报料任务ID不为空，则新任务报料任务ID为父任务的报料任务ID
                wmTaskNew.setOrderTaskId(wmTaskParentNew.getOrderTaskId());
            }
        }
        else{
            wmTaskNew.setPid(IWmTaskService.ROOT_PID_VALUE);
            wmTaskNew.setAncestors(IWmTaskService.ANCESTORS);
        }

        addWmTask(wmTaskNew);
        wmTaskNew.setHasChild(null); //不更新该属性，addWmTask方法中已经更新过
        return wmTaskNew;
    }

    //复制任务BOM
    private void copyTaskBomSkillChange(WmTask wmTaskOfDesign, WmTask rootProduceTaskOfNextVersion){
        //获取设计起点任务的物料清单
        List<WmTaskBom> wmTaskBomList = wmTaskBomService.listByWmTaskIdAndVersion(wmTaskOfDesign.getId(), wmTaskOfDesign.getCurrentVersion());
        //生成下一版本的物料BOM
        for(WmTaskBom wmTaskBomItem: wmTaskBomList) {
            WmTaskBom wmTaskBom = new WmTaskBom();
            wmTaskBom.setSpecification(wmTaskBomItem.getSpecification());
            wmTaskBom.setCode(wmTaskBomItem.getCode());
            wmTaskBom.setName(wmTaskBomItem.getName());
            wmTaskBom.setWmTaskId(rootProduceTaskOfNextVersion.getId()); //报料任务ID
            wmTaskBom.setUnitOfMeasure(wmTaskBomItem.getUnitOfMeasure());
            wmTaskBom.setItemType(wmTaskBomItem.getItemType());
            wmTaskBom.setStatus(UserConstant.TASKBOM_PREPARE);
            wmTaskBom.setProcessNo(wmTaskBomItem.getProcessNo());
            wmTaskBom.setGotowhere(wmTaskBomItem.getGotowhere());
            wmTaskBom.setSize(wmTaskBomItem.getSize());
            wmTaskBom.setMaterial(wmTaskBomItem.getMaterial());
            wmTaskBom.setRemark(wmTaskBomItem.getRemark());
            wmTaskBom.setCaiLiao(wmTaskBomItem.getCaiLiao());
            wmTaskBom.setGuiGe(wmTaskBomItem.getGuiGe());
            wmTaskBom.setGbNumber(wmTaskBomItem.getGbNumber());
            wmTaskBom.setMingCheng(wmTaskBomItem.getMingCheng());
            wmTaskBom.setOtherRequire(wmTaskBomItem.getOtherRequire());
            wmTaskBom.setNeedNum(wmTaskBomItem.getNeedNum());
            wmTaskBom.setTotalWeight(wmTaskBomItem.getTotalWeight());
            wmTaskBom.setPurchaseNum(wmTaskBomItem.getPurchaseNum());
            wmTaskBom.setSysOrgCode(wmTaskBomItem.getSysOrgCode());
            wmTaskBom.setTenantId(wmTaskBomItem.getTenantId());
            wmTaskBom.setCurrentVersion(rootProduceTaskOfNextVersion.getCurrentVersion());
            wmTaskBomService.save(wmTaskBom);
        }
    }
}
